#!/usr/bin/env python3
"""
串口测试程序 - RK3588端
用于测试与ESP32的串口通信
"""

import serial
import time
import threading
import sys

class SerialTester:
    def __init__(self, port='/dev/ttyUSB0', baudrate=115200):
        self.port = port
        self.baudrate = baudrate
        self.serial_conn = None
        self.running = False
        self.read_thread = None
        
    def connect(self):
        """连接串口"""
        try:
            self.serial_conn = serial.Serial(
                port=self.port,
                baudrate=self.baudrate,
                timeout=1,
                bytesize=serial.EIGHTBITS,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE
            )
            print(f"✅ 连接成功: {self.port} @ {self.baudrate}")
            return True
        except Exception as e:
            print(f"❌ 连接失败: {e}")
            return False
    
    def disconnect(self):
        """断开连接"""
        self.running = False
        if self.read_thread:
            self.read_thread.join()
        if self.serial_conn and self.serial_conn.is_open:
            self.serial_conn.close()
            print("📴 串口已断开")
    
    def read_loop(self):
        """读取循环"""
        while self.running:
            try:
                if self.serial_conn and self.serial_conn.in_waiting > 0:
                    data = self.serial_conn.readline().decode('utf-8', errors='ignore').strip()
                    if data:
                        print(f"📥 收到: {data}")
            except Exception as e:
                print(f"❌ 读取错误: {e}")
                break
            time.sleep(0.01)
    
    def send_message(self, message):
        """发送消息"""
        if self.serial_conn and self.serial_conn.is_open:
            try:
                self.serial_conn.write((message + '\n').encode())
                print(f"📤 发送: {message}")
            except Exception as e:
                print(f"❌ 发送错误: {e}")
        else:
            print("❌ 串口未连接")
    
    def start_reading(self):
        """开始读取线程"""
        self.running = True
        self.read_thread = threading.Thread(target=self.read_loop, daemon=True)
        self.read_thread.start()
    
    def interactive_mode(self):
        """交互模式"""
        print("\n=== 串口测试交互模式 ===")
        print("输入消息并按回车发送")
        print("特殊命令:")
        print("  /quit  - 退出")
        print("  /test  - 发送测试序列")
        print("  /help  - 显示帮助")
        print("  /clear - 清屏")
        
        while True:
            try:
                user_input = input("发送> ").strip()
                
                if user_input == '/quit':
                    break
                elif user_input == '/test':
                    self.run_test_sequence()
                elif user_input == '/help':
                    self.send_message("help")
                elif user_input == '/clear':
                    print("\033[2J\033[H")  # 清屏
                elif user_input:
                    self.send_message(user_input)
                    
            except KeyboardInterrupt:
                break
            except Exception as e:
                print(f"❌ 输入错误: {e}")
    
    def run_test_sequence(self):
        """运行测试序列"""
        print("\n🧪 开始测试序列...")
        
        test_messages = [
            "hello",
            "time", 
            "test message 123",
            "你好世界",
            "help"
        ]
        
        for msg in test_messages:
            print(f"\n📤 测试发送: {msg}")
            self.send_message(msg)
            time.sleep(1)
        
        print("\n✅ 测试序列完成")
    
    def monitor_mode(self):
        """监控模式 - 只接收不发送"""
        print("\n=== 串口监控模式 ===")
        print("只接收数据，按Ctrl+C退出")
        
        try:
            while True:
                time.sleep(0.1)
        except KeyboardInterrupt:
            print("\n监控结束")

def main():
    """主函数"""
    print("=== ESP32 串口测试工具 ===")
    
    # 检查命令行参数
    port = '/dev/ttyUSB0'
    if len(sys.argv) > 1:
        port = sys.argv[1]
    
    # 创建测试器
    tester = SerialTester(port)
    
    # 连接
    if not tester.connect():
        sys.exit(1)
    
    # 开始读取
    tester.start_reading()
    
    # 等待ESP32启动
    print("⏳ 等待ESP32启动...")
    time.sleep(2)
    
    try:
        # 选择模式
        print("\n请选择模式:")
        print("1 - 交互模式 (可发送消息)")
        print("2 - 监控模式 (只接收)")
        print("3 - 测试序列")
        
        choice = input("选择 (1/2/3): ").strip()
        
        if choice == '1':
            tester.interactive_mode()
        elif choice == '2':
            tester.monitor_mode()
        elif choice == '3':
            tester.run_test_sequence()
            time.sleep(5)  # 等待响应
        else:
            print("❌ 无效选择，使用交互模式")
            tester.interactive_mode()
            
    except Exception as e:
        print(f"❌ 运行错误: {e}")
    finally:
        tester.disconnect()

if __name__ == "__main__":
    main() 